<script setup>
import { ref, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {
  artGetInfoService,
  artAddService,
  artUpdateService
} from '@/api/article'
import { QuillEditor } from '@vueup/vue-quill'
import { baseURL } from '@/utils/request'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ChannelSelect from './ChannelSelect.vue'
import axios from 'axios'

const loading = ref(false)

const emit = defineEmits(['success'])

const editor = ref()

const drawer = ref(false)

const imageUrl = ref('')

const formRef = ref()

const formData = ref({
  id: '',
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})

const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  cover_img: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

// 发布文章
const onPublish = async (state) => {
  await formRef.value.validate()
  formData.value.state = state
  const fd = new FormData()
  for (let key in formData.value) {
    fd.append(key, formData.value[key])
  }
  if (formData.value.id) {
    const { data } = await artUpdateService(fd)
    ElMessage.success(data.message)
    emit('success')
  } else {
    const { data } = await artAddService(fd)
    ElMessage.success(data.message)
    emit('success', 'add')
  }
  drawer.value = false
}
// 封面本地预览
const onSelectFile = (file) => {
  imageUrl.value = URL.createObjectURL(file.raw)
  formData.value.cover_img = file.raw
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
// 清空数据
const clearData = () => {
  formData.value = {
    id: '',
    title: '',
    cate_id: '',
    content: '',
    cover_img: '',
    state: ''
  }
  imageUrl.value = ''
  nextTick(() => {
    editor.value.setHTML('')
  })
}

// 打开抽屉
const open = async (row) => {
  clearData()
  loading.value = true
  drawer.value = true
  if (row && row.id) {
    const {
      data: { data }
    } = await artGetInfoService(row.id)
    formData.value = data
    imageUrl.value = baseURL + formData.value.cover_img
    formData.value.cover_img = await imageUrlToFile(
      imageUrl.value,
      formData.value.cover_img
    )
  } else {
    clearData()
  }
  loading.value = false
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer
    v-model="drawer"
    :title="formData.id ? '编辑文章' : '添加文章'"
    size="50%"
  >
    <el-form
      :model="formData"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input placeholder="请输入标题" v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <ChannelSelect v-model="formData.cate_id" width="100%"></ChannelSelect>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :on-change="onSelectFile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <QuillEditor
            ref="editor"
            theme="snow"
            v-model:content="formData.content"
            contentType="html"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
